import React, { useState, useEffect } from 'react';
import { 
  Card, 
  List, 
  Button, 
  Space, 
  Tag, 
  Typography, 
  Avatar, 
  Popconfirm,
  message,
  Input,
  Select,
  Row,
  Col
} from 'antd';
import { 
  FileWordOutlined, 
  FilePdfOutlined, 
  FilePptOutlined, 
  FileExcelOutlined,
  EyeOutlined,
  DeleteOutlined,
  DownloadOutlined,
  SearchOutlined,
  FolderOutlined
} from '@ant-design/icons';
import { FileViewerTrigger } from '../FileViewer/FileViewer';
import { formatFileSize, formatDate } from '../../utils';
import './DocumentManager.scss';

const { Text, Title } = Typography;
const { Search } = Input;
const { Option } = Select;

const DocumentManager = ({ documents = [], onDelete, onView, className }) => {
  const [filteredDocs, setFilteredDocs] = useState(documents);
  const [searchText, setSearchText] = useState('');
  const [typeFilter, setTypeFilter] = useState('all');
  const [sortBy, setSortBy] = useState('date');

  useEffect(() => {
    filterAndSortDocuments();
  }, [documents, searchText, typeFilter, sortBy]);

  const filterAndSortDocuments = () => {
    let filtered = [...documents];

    // 搜索过滤
    if (searchText) {
      filtered = filtered.filter(doc =>
        doc.name.toLowerCase().includes(searchText.toLowerCase())
      );
    }

    // 类型过滤
    if (typeFilter !== 'all') {
      filtered = filtered.filter(doc => doc.type === typeFilter);
    }

    // 排序
    filtered.sort((a, b) => {
      switch (sortBy) {
        case 'name':
          return a.name.localeCompare(b.name);
        case 'size':
          return b.size - a.size;
        case 'type':
          return a.type.localeCompare(b.type);
        case 'date':
        default:
          return new Date(b.uploadedAt || b.createdAt) - new Date(a.uploadedAt || a.createdAt);
      }
    });

    setFilteredDocs(filtered);
  };

  const getFileIcon = (type) => {
    const iconProps = { style: { fontSize: 32 } };
    
    switch (type) {
      case 'word':
        return <FileWordOutlined {...iconProps} style={{ ...iconProps.style, color: '#1890ff' }} />;
      case 'pdf':
        return <FilePdfOutlined {...iconProps} style={{ ...iconProps.style, color: '#f5222d' }} />;
      case 'ppt':
        return <FilePptOutlined {...iconProps} style={{ ...iconProps.style, color: '#fa8c16' }} />;
      case 'excel':
        return <FileExcelOutlined {...iconProps} style={{ ...iconProps.style, color: '#52c41a' }} />;
      default:
        return <FolderOutlined {...iconProps} style={{ ...iconProps.style, color: '#666' }} />;
    }
  };

  const getTypeTag = (type) => {
    const typeMap = {
      'word': { color: 'blue', text: 'Word' },
      'pdf': { color: 'red', text: 'PDF' },
      'ppt': { color: 'orange', text: 'PPT' },
      'excel': { color: 'green', text: 'Excel' },
      'txt': { color: 'default', text: 'Text' },
      'csv': { color: 'default', text: 'CSV' }
    };
    
    const config = typeMap[type] || { color: 'default', text: type.toUpperCase() };
    return <Tag color={config.color}>{config.text}</Tag>;
  };

  const handleDownload = (doc) => {
    if (doc.fileUrl) {
      const link = document.createElement('a');
      link.href = doc.fileUrl;
      link.download = doc.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      message.success('文件下载开始');
    } else {
      message.error('文件链接不可用');
    }
  };

  const handleDelete = (doc) => {
    onDelete && onDelete(doc);
  };

  const handleView = (doc) => {
    onView && onView(doc);
  };

  const getFileTypeOptions = () => {
    const types = [...new Set(documents.map(doc => doc.type))];
    return types.map(type => (
      <Option key={type} value={type}>
        {type.charAt(0).toUpperCase() + type.slice(1)}
      </Option>
    ));
  };

  return (
    <div className={`document-manager ${className || ''}`}>
      <Card>
        <div className="manager-header">
          <Title level={4} style={{ margin: 0 }}>
            文档管理 ({filteredDocs.length})
          </Title>
          
          <div className="manager-controls">
            <Row gutter={[8, 8]} align="middle">
              <Col xs={24} sm={8}>
                <Search
                  placeholder="搜索文档名称"
                  value={searchText}
                  onChange={(e) => setSearchText(e.target.value)}
                  allowClear
                />
              </Col>
              <Col xs={12} sm={4}>
                <Select
                  placeholder="文件类型"
                  value={typeFilter}
                  onChange={setTypeFilter}
                  style={{ width: '100%' }}
                >
                  <Option value="all">全部类型</Option>
                  {getFileTypeOptions()}
                </Select>
              </Col>
              <Col xs={12} sm={4}>
                <Select
                  placeholder="排序方式"
                  value={sortBy}
                  onChange={setSortBy}
                  style={{ width: '100%' }}
                >
                  <Option value="date">按日期</Option>
                  <Option value="name">按名称</Option>
                  <Option value="size">按大小</Option>
                  <Option value="type">按类型</Option>
                </Select>
              </Col>
            </Row>
          </div>
        </div>

        {filteredDocs.length === 0 ? (
          <div className="empty-state">
            <FolderOutlined style={{ fontSize: 48, color: '#d9d9d9' }} />
            <p>暂无文档</p>
          </div>
        ) : (
          <List
            itemLayout="horizontal"
            dataSource={filteredDocs}
            renderItem={doc => (
              <List.Item
                className="document-item"
                actions={[
                  <FileViewerTrigger
                    key="preview"
                    fileUrl={doc.fileUrl}
                    fileName={doc.name}
                    buttonProps={{
                      type: "link",
                      icon: <EyeOutlined />,
                      size: "small"
                    }}
                  >
                    预览
                  </FileViewerTrigger>,
                  <Button
                    key="download"
                    type="link"
                    size="small"
                    icon={<DownloadOutlined />}
                    onClick={() => handleDownload(doc)}
                  >
                    下载
                  </Button>,
                  <Popconfirm
                    key="delete"
                    title="确定要删除这个文档吗？"
                    onConfirm={() => handleDelete(doc)}
                    okText="确定"
                    cancelText="取消"
                  >
                    <Button
                      type="link"
                      size="small"
                      danger
                      icon={<DeleteOutlined />}
                    >
                      删除
                    </Button>
                  </Popconfirm>
                ]}
              >
                <List.Item.Meta
                  avatar={getFileIcon(doc.type)}
                  title={
                    <div className="document-title">
                      <Text strong className="doc-name" title={doc.name}>
                        {doc.name}
                      </Text>
                      {getTypeTag(doc.type)}
                    </div>
                  }
                  description={
                    <Space direction="vertical" size="small">
                      <Space size="middle">
                        <Text type="secondary">
                          大小: {formatFileSize(doc.size)}
                        </Text>
                        <Text type="secondary">
                          上传: {formatDate(doc.uploadedAt || doc.createdAt, 'YYYY-MM-DD HH:mm')}
                        </Text>
                      </Space>
                      {doc.messages && doc.messages.length > 0 && (
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {doc.messages[0]}
                        </Text>
                      )}
                    </Space>
                  }
                />
              </List.Item>
            )}
          />
        )}
      </Card>
    </div>
  );
};

export default DocumentManager;